using System.Text;

namespace RollManager.Library.Utils
{
    /// <summary>
    /// Class designed to add the finding of tags deliminted by square brackets in a string and replace them.
    /// </summary>
    public class StringParser
    {
        private int m_nextIdx;
        private readonly char[] m_originalStr;
        private readonly StringBuilder m_finalStr;

        public string NextPiece
        {
            get
            {
                bool insidePiece = false;
                StringBuilder pieceBuilder = new StringBuilder();

                // walk the original string to find the next piece
                while( m_nextIdx < m_originalStr.Length )
                {
                    char nextChar = m_originalStr[ m_nextIdx++ ];

                    if( nextChar == '[' )
                    {
                        // we entered a piece
                        insidePiece = true;
                    }
                    else if( nextChar == ']' && insidePiece )
                    {
                        // we exited a piece, return it.
                        return pieceBuilder.ToString();
                    }
                    else if( insidePiece )
                    {
                        // add regular character inside piece to piece builder
                        pieceBuilder.Append( nextChar );
                    }
                    else
                    {
                        // add regular character to final string
                        m_finalStr.Append( nextChar );
                    }
                }

                // we never found a piece and the string is finished.
                return null;
            }
        }

        public StringParser( string str )
        {
            m_originalStr = str.ToCharArray();
            m_finalStr = new StringBuilder();
        }

        public static StringParser operator +( StringParser a, object b )
        {
            a.Append( b );
            return a;
        }

        public void Append( object str )
        {
            m_finalStr.Append( str );
        }

        public void AppendFormat( string str, params object[] args )
        {
            m_finalStr.AppendFormat( str, args );
        }

        public override string ToString()
        {
            return m_finalStr.ToString();
        }
    }
}